package com.iweb.dao;

import com.iweb.pojo.Order;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class OrderDaoImpl implements OrderDao {
	private PreparedStatement pst;
	private Connection conn;
	private ResultSet rs;

	public OrderDaoImpl(Connection connection) {
		this.conn = connection;
	}

	@Override
	public void addOrder(Order order) throws Exception {
//        String  sql="insert into tb_order values (?,?,?)";
//        pst=conn.prepareStatement(sql);
//        pst.setString(1,order.getAid());
//        pst.setString(2,order.getGid());
//        pst.setInt(3,1);
//        pst.executeUpdate();
//        System.out.println(order);
		if (order.getAid() == null || order.getGid() == null)
			return;

		String sql = "select orders from tb_order where aid  = ? and gid = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setObject(1, order.getAid());
		pst.setObject(2, order.getGid());
		ResultSet rs = pst.executeQuery();
		if (rs.next()) {
			//某人订购某商品的数量
			Integer orderNum = rs.getInt(1);
			//如果购物车里已经有某用户添加某商品的记录，则使用update语句
			if (orderNum != null) {
				orderNum += order.getOrders();
				sql = "update tb_order set orders = ? where aid  = ? and gid = ?";
				pst = conn.prepareStatement(sql);
				pst.setObject(1, orderNum);
				pst.setObject(2, order.getAid());
				pst.setObject(3, order.getGid());
				pst.executeUpdate();
			}
		} else { //如果没有某用户的添加记录，则使用insert语句
			sql = "insert into tb_order(aid,gid,orders) values (?,?,?)";
			pst = conn.prepareStatement(sql);
			pst.setString(1, order.getAid());
			pst.setString(2, order.getGid());
			pst.setInt(3, order.getOrders());
			pst.executeUpdate();
//			System.out.println(order);
		}
	}
}
